package net.tarine.gastronomi.client.widgets;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;

public class MessagePanel extends FlowPanel {
	
	public static final int INFO = 0;
	public static final int WARN = 1;
	public static final int ERROR = 2;
	
	private static final int INFO_SHOW_TIME = 5000;
	
	public MessagePanel() {
		this.setHeight("3em");
	}
	
	
//	private void addMessage(String message, int type) {
//		this.add(new MessageInstance(this, message, type));
//	}
	
	public void addInfo(String info) {
		this.add(new TempMessageInstance(this, info, INFO));
	}
	
	public void addWarning(String warning) {
		this.add(new MessageInstance(this, warning, WARN));
	}
	
	public void addError(String error) {
		this.add(new MessageInstance(this, error, ERROR));
	}
	
	public void removeMessage(MessageInstance inst ) {
		this.remove(inst);
	}
	
	//Gestione messaggi a scomparsa
	
	
	private void removeTempMessage(TempMessageInstance inst ) {
		this.remove(inst);
	}
	
	//Inner classes
	
	private class MessageInstance extends HorizontalPanel {
		
		public MessageInstance(MessagePanel p, String msg, int type) {
			final MessagePanel parent=p;
			final MessageInstance thisInstance = this;
			Button ok = new Button(" OK ");
			HTML label = makeLabel(msg, type);
			this.add(label);
			this.add(ok);
			ok.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					parent.removeMessage(thisInstance);
				}
			});
		}
	}
	
	private class TempMessageInstance extends HorizontalPanel {
		
		public TempMessageInstance(MessagePanel parent, String msg, int type) {
			final MessagePanel p=parent;
			final TempMessageInstance thisInstance = this;
			final HTML label = makeLabel(msg, type);
			this.add(label);
			Timer t = new Timer() {
				public void run() {
					thisInstance.remove(label);
					p.removeTempMessage(thisInstance);
				}
			};
			t.schedule(INFO_SHOW_TIME);
		}
	}
	
	private HTML makeLabel(String msg, int type) {
		String style = null;
		if (type == INFO) {
			msg = "<img src='img/dialog-information.png' style='vertical-align:middle' />&nbsp;" + msg;
			style = "message-info";
		}
		if (type == WARN) {
			msg = "<img src='img/dialog-warning.png' style='vertical-align:middle' />&nbsp;" + msg;
			style = "message-warn";
		}
		if (type == ERROR) {
			msg = "<img src='img/dialog-error.png' style='vertical-align:middle' />&nbsp;" + msg;
			style = "message-error";
		}
		HTML label = new HTML(msg);
		label.setStyleName(style);
		return label;
	}
}
